// Copyright Notice:
//				validate.js v1.0.2
//			Copyright@2008 - OpenSiteMobile
//				All rights reserved
// ==========================================================================
//			http://www.opensitemobile.com
// ==========================================================================
// Contact Information:
//			Author: Dwight Vietzke
//			Email:  dwight_vietzke@yahoo.com

/*
	OpenSiteMobile additional dojo type validation functions
*/

dojo.provide("msos.validate");
dojo.require("msos.common");

msos.validate.check_hex_color = function(hex) {
    if (msos.common.var_is_empty(hex)) return null;
    hex = hex.toString();
    if (hex.length == 7) hex = hex.substr(1);
    if (hex.length != 6) return false;
    hex = hex.toUpperCase();

    var chars = '0123456789ABCDEF';
    var out   = '';

    for (var i=0; i<hex.length; i++) {
	var schar = hex.charAt(i);
	if (chars.indexOf(schar) != -1) { out += schar; }
    }
    if (out.length != 6) { return false; }
    return out;
}

// Browser independent color validation
msos.validate.browser_color_to_hex = function(v) {
    if (!v) {
        // Alert (red) that conversion died!
        return '#FF0000';
    }
    var output = '';

    // returns the hex representation of one byte (2 digits)
    function hex(d) { return (d < 16) ? ("0" + d.toString(16)) : d.toString(16); };

    if (typeof v == "number") {
	// we're talking to IE here
	var r = v & 0xFF;
	var g = (v >> 8) & 0xFF;
	var b = (v >> 16) & 0xFF;
	output = hex(r) + hex(g) + hex(b);
    }
    if (v.substr(0, 3) == "rgb") {
	// in rgb(...) form -- Mozilla
	var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
	if (v.match(re)) {
	    var r = parseInt(RegExp.$1);
	    var g = parseInt(RegExp.$2);
	    var b = parseInt(RegExp.$3);
	    output = hex(r) + hex(g) + hex(b);
	}
    }
    if (v.length == 7) {
        // #FFFFFF hex form
        output = v.substr(1);
    }
    if (output.length != 6) {
        // Alert (green) that conversion died!
        output = '00FF00';
    }

    output = output.toUpperCase();

    var chars = '0123456789ABCDEF';
    var out   = '';

    for (var i=0; i<output.length; i++) {
	var schar = output.charAt(i);
	if (chars.indexOf(schar) != -1) { out += schar; }
    }
    if (out.length == 6)	{ return ('#' + output); }
    else			{ return '#0000FF';	 } // Conversion died!
}

// Simple 'get numeric part' of a string
msos.validate.get_numeric_substring = function(value) {
    var numb = parseInt(value);
    if (isNaN(numb)) { numb = ''; }
    return numb;
}

// Simple 'is string all integers' function
msos.validate.is_int_number = function(inString) {
    var refString = "1234567890";

    if (inString.length == 0)	{ return false; }
    if (inString <= 0)		{ return false; }

    for (count = 0; count < inString.length; count++) {
	tempChar = inString.substring(count, count+1);
	if (refString.indexOf(tempChar, 0) == -1) { return false; }
    }
    return true;
}